package chapter05.cookie.example;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet("/LastAccessServlet")
public class LastAccessServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        String lastAccessTime = null;

        // 获取所有的 cookie，并将这些 cookie 存放在数组中
        Cookie[] cookies = request.getCookies();

        // 遍历 cookies 数组
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            if ("lastAccess".equals(cookies[i].getName())) {
                // 如果 cookie 的名称为 lastAccess, 则获取该 cookie 的值
                lastAccessTime = cookies[i].getValue();
                break;
            }
        }

        // 判断是否存在名称为 lastAccess 的 cookie
        if (lastAccessTime == null) {
            response.getWriter().print("您是首次访问本站！！！");
        } else {
            response.getWriter().print("您上次的访问时间是： " + lastAccessTime);
        }

        // 创建 cookie，将当前时间作为 cookie 的值发送给客户端
        String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        Cookie cookie = new Cookie("lastAccess", currentTime);

        cookie.setMaxAge(24 * 60 * 60);

        // 发送 cookie
        response.addCookie(cookie);
    }

    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}